<template>
  <div class="register-page op-fullscreen">
    <VanNavBar title="请注册" left-text="返回" left-arrow @click-left="onClickLeft" />
    <VanForm class="register-page__form" @submit="onSubmit">
      <VanCellGroup inset>
        <VanField
            v-model="registerForm.userName"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <VanField
            v-model="registerForm.password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
        <VanField
            v-model="registerForm.confirmPassword"
            name="confirmPassword"
            label="确认密码"
            placeholder="确认密码"
            :rules="[{ required: true, message: '请再次填写密码' }, { validator: validatePassword, message: '两次输入的密码不一致' }]"
        />
      </VanCellGroup>
      <div style="margin: 16px">
        <VanButton round block type="primary" native-type="submit">提交</VanButton>
      </div>
    </VanForm>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import { reqRegister } from '@/api/user';
import type { registerForm, responseData } from '@/api/user/type.ts';

// 获取路由器
let $router = useRouter();

// 注册输入的数据
let registerForm: registerForm = reactive({
  userName: '',
  password: '',
  confirmPassword: ''
});

// 返回
const onClickLeft = () => history.back();

// 验证两次输入的密码是否一致
const validatePassword = (value: string) => {
  return value === registerForm.password;
};

const onSubmit = async () => {
  try {
    let result: responseData = await reqRegister(registerForm);
    if (result.code === 1) {
      ElNotification({
        type: 'success',
        message: '注册成功，请登录'
      });
      $router.push('/login');
    } else {
      ElNotification({
        type: 'error',
        message: result.msg
      });
    }
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message
    });
  }
};
</script>

<style scoped>
.register-page {
  .register-page__form {
    margin-top: 100px;
  }
}
</style>